package com.durian.base.rxhttp.param

import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.net.URLConnection

/**
 * 说明：keyValuePair
 * <p/>
 * 作者：Fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2020/04/24 19:32
 * <p/>
 * 版本：version 1.0
 */
class KeyValuePair(
        val key: String,
        val value: Any? = null,
        val isEncoded: Boolean = false,
        val file: File? = null
) {

    override fun equals(other: Any?): Boolean {
        if (other is KeyValuePair) {
            return other.key == key
        }
        return super.equals(other)
    }
}

class KeyFilePair(
        val key: String,
        val file: File,
        private val requestBody: RequestBody? = null
) {
    fun checkFile(): Boolean {
        return file.isFile && file.exists()
    }

    fun getRequestBody(): RequestBody {
        return requestBody ?: file.asRequestBody(getMediaType())
    }

    private fun getMediaType(): MediaType? {
        var contentType = URLConnection.guessContentTypeFromName(file.name)
        if (contentType == null || contentType.isEmpty()) {
            contentType = "application/octet-stream"
        }
        return contentType.toMediaTypeOrNull()
    }
}